package com.azt.provider.impl;

import com.azt.api.pojo.Address;
import com.azt.api.service.AddressService;
import com.azt.provider.mapper.AddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
	
	@Autowired
	private AddressMapper addressMapper;

	@Override
	public Address getAddressById(int id) {
		return addressMapper.selectByPrimaryKey(id);
	}

	@Override
	public Address getAddressByIdWithName(int addressId) {
		return addressMapper.getAddressByIdWithName(addressId);
	}

	@Override
	public void setDefaultAddress(int userId, int addressId) {
		//先取消该用户的所有默认地址
		Example example = new Example(Address.class);
		{
			Address address = new Address();
			address.setUserId(userId);
			address.setRemoved(0);
			example.createCriteria().andEqualTo(address);
		}
		{
			Address address = new Address();
			address.setSetdefault(0);
			addressMapper.updateByExampleSelective(address, example);
		}
		//然后将该地址置为默认
		Address address = new Address(addressId);
		address.setSetdefault(1);
		addressMapper.updateByPrimaryKeySelective(address);
	}

	@Override
	public List<Address> findUserAddress(int userId) {
		return addressMapper.findUserAddress(userId);
	}

	@Override
	public void addAddress(Address address) {
		address.setRemoved(0);
		address.setCreatetime(new Date());
		addressMapper.insertSelective(address);
		if(address.getSetdefault() != null && address.getSetdefault() == 1) {
			setDefaultAddress(address.getUserId(), address.getId());
		}
	}

	@Override
	public void updateAddress(Address address) {
		address.setUpdatetime(new Date());
		addressMapper.updateByPrimaryKeySelective(address);
		if(address.getSetdefault() != null && address.getSetdefault() == 1) {
			setDefaultAddress(address.getUserId(), address.getId());
		}
	}

	@Override
	public void removeAddress(int addressId) {
		Address address = new Address(addressId);
		address.setRemoved(1);
		updateAddress(address);
	}
}
